import datetime

from flask import session

from webapp.extensions import AppException
from webapp.models import Grade, db, User, UsersJobs, Job, UsersRoles, VTeacher, TeacherBindTime


class TeacherService:
    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        nickname = kwargs.get('nickName')
        not_empty = nickname or create_times
        query = []
        if nickname:
            query.append((VTeacher.nick_name.like(f'%{nickname}%')))
        if create_times and len(create_times) >= 2:
            query.append((VTeacher.create_time.between(create_times[0], create_times[1])))
        results = VTeacher.query.filter(*query).paginate(
            int(page) + 1, per_page=int(size),
            error_out=False)
        return results

    @staticmethod
    def find_by_id(id):
        grade = db.session.query(Grade).filter(Grade.id == id).one_or_none()
        if grade is None:
            raise AppException(f'您所操作的对象已不存在!')
        return grade

    @staticmethod
    def timeSetting(id, params):
        TeacherBindTime.query.filter(TeacherBindTime.teacherId == id).delete()
        db.session.commit()
        choiceDay = ','.join(str(i) for i in params['choiceDay'])
        choiceSection = ','.join(str(i) for i in params['choiceSection'])
        choiceWeek = ','.join(str(i) for i in params['choiceWeek'])
        data = user = session["user"]

        teacherbindtime = TeacherBindTime(
            teacherId=id,
            weeknum=choiceWeek,
            order=choiceSection,
            weekday=choiceDay,
            create_by=data["username"]
        )
        db.session.add(teacherbindtime)
        db.session.commit()

    @staticmethod
    def find_by_teacherid(id):
        teacherbindtime = db.session.query(TeacherBindTime).filter(TeacherBindTime.teacherId == id).one_or_none()

        return teacherbindtime